package com.myacg.core.task;

import java.util.Date;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;


/**
 * 倒计时任务管理器
 * @author Administrator
 *
 */
public class KeepTaskManager {
	private ConcurrentMap<String, KeepTask>  map;
	private boolean ispause;
	private static KeepTaskManager keepTaskManage;
	private int i;
	private KeepTaskManager(){
		 map= new ConcurrentHashMap<>();
		//启动定时任务
		startAllTask();
	}
	
	public void continueTasks(){
		ispause=false;
	}
	public void pauseTasks(){
		ispause=true;
	}
	
	/**
	 * 获取倒计时任务管理器
	 * @return
	 */
	public static KeepTaskManager getInstance(){
		if(keepTaskManage==null){
			keepTaskManage=new KeepTaskManager();
		}
		return keepTaskManage;
	}
	
	/**
	 * 加入一个任务并为该任务 分配一个id
	 * @param task
	 */
	public synchronized void addTask(KeepTask task){
		if(task.getId()==null){
			task.id=("CD-"+new Date().getTime()+"-"+i++);
		} 
		this.map.put(task.getId(), task);
		System.out.println("add KeepTask: "+ task.id);
	}
    
	/**
	 * 启动所有任务的方法
	 */
	private void startAllTask(){
		new Thread( new  Runnable() {
			public void run() {
				while(true){
				 //执行队列中尚存在的任务	
					 if(!ispause){
						Set<String> set = map.keySet();
						   for (String key : set) {
							     KeepTask task = map.get(key);
							     if(task.isOver){ //死亡条件不同
							    	 map.remove(task.getId()); //移除
							    	 task.overExecute();
							    	 System.out.println("KeepTaskManager remove task :" + task.getId());
							     }else if(task.initSecond%task.howSecond == 0){ //每到howSecond 个间隔 执行一次
							    	 task.excute();
							     }
							     //值变大了置零
							     if(task.initSecond==10000000){
							    	 task.initSecond=0;
							     }else{
							    	 task.initSecond++;
							     }
						   }
					 }
				   //休眠一毫秒
			       try { Thread.sleep(1); } catch (InterruptedException e) { }
				}
		 }
		}).start();
		
		
	}
	/**
	 * 获取任务
	 * @param id
	 * @return
	 */
	public KeepTask getTask(String id){
		return  this.map.get(id);
	}
	/**
	 * 返回当前状态
	 * @return
	 */
	public  boolean  isPause(){
		return this.ispause;
	}
	
	/**
	 * Demo
	 * @param args
	 */
	public static void main(String[] args) {
		KeepTaskManager.getInstance();
		KeepTaskManager.getInstance().addTask(new KeepTask(300) {
			int i=0;
			@Override
			public void secondExecute() {
				System.out.println("secondExecute"+i);
				i++;
				if(i==3){
					this.over();
				}
			}
			@Override
			public void overExecute() {
				System.out.println("overExecute");
			}
			 
		}); 
		 
	}
	
	
}
